<?php

namespace catchAdmin\visitPlan\controller;

use app\common\lib\ZhyxBeanstalkd;
use catcher\base\CatchRequest;
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\visitPlan\model\VisitPlanDetail as VisitPlanDetailModel;
use catcher\Code;
use catcher\exceptions\CatchException;
use catcher\exceptions\FailedException;
use catcher\exceptions\ValidateFailedException;
use think\Response;

class VisitPlanDetail extends CatchController
{

    protected $visitPlanDetailModel;

    /**
     *
     * @time 2022/10/17 17:57
     * @param VisitPlanDetailModel $visitPlanDetailModel
     * @return mixed
     */
    public function __construct(VisitPlanDetailModel $visitPlanDetailModel)
    {
        $this->visitPlanDetailModel = $visitPlanDetailModel;
    }

    /**
     * 获取就诊人数
     * @param Request $request
     * @return \think\response\Json
     */
    public function getVisitPlanCount(CatchRequest $request): \think\response\Json
    {
        $planId = $request->param("visit_id", "", "string");

        if (empty($planId)) {
            throw new FailedException("复诊计划id不能为空");
        }
        $visitCountArr = $this->visitPlanDetailModel->getVisitCount($planId);
        return CatchResponse::success($visitCountArr);
    }

    /**
     *
     * @time 2022/10/17 17:57
     * @return Response
     */
    public function index(CatchRequest $request): Response
    {
        return CatchResponse::success();
    }

    /**
     *
     * @time 2022/10/17 17:57
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        try {
            $postData = request()->param("", [], "htmlspecialchars,strip_tags,htmlentities");
            $result = $this->visitPlanDetailModel->withoutField(["_id", "created_at", "updated_at"])->where('id', "=", $postData["id"])->find();
            if (empty($result)) {
                throw new FailedException("没有找到该患者信息");
            }
            $result["next_visit_time"] = $postData["next_visit_time"] ?? "";
            $result["creator_id"] = $postData['creator_id'] ?? "";
            $result["push_type"] = $postData["push_type"] ?? $result["push_type"];
            $result["period_content"] = $postData["period_content"] ?? $result["period_content"];
            $rnd = $result->save($result->toArray());
            if ($rnd !== false) {
                //根据复诊主键id获取提前天数
                $delay = 0;
                $planResult = (new \catchAdmin\visitPlan\model\VisitPlan())->where("id", "=", $result["visit_id"])->find();
                $remindCount = $planResult["remind_count"] ?? 0;

                $diffDays = date_diff(date_create($postData["next_visit_time"]), date_create(date("Y-m-d")), true);
                if ($diffDays->days > 0 && $diffDays->days > $remindCount) {
                    $delay = ($diffDays->days - $remindCount) * 86400 + 8 * 60;
                }
                $pushData = [
                    'visit_id' => $result["id"],
                    'patientList' => [$result->toArray()]
                ];

                ZhyxBeanstalkd::getInstance()->beansTalk->useTube("sendVistMessage")->put(json_encode($pushData, JSON_THROW_ON_ERROR), 0, $delay);
            }
            return CatchResponse::success();
        } catch (\Exception $exception) {
            throw new FailedException("更新失败：" . $exception->getMessage());
        }

    }

    /**
     *
     * @time 2022/10/17 17:57
     * @param $id
     * @return Response
     */
    public function read($id, CatchRequest $request): Response
    {
        $type = $request->param("type", 1, "int");
        $result = $this->visitPlanDetailModel->getLists($id, $type);

        $result = array_merge($result, ["code" => Code::SUCCESS, "message" => "success"]);
        return json($result);
    }

    /**
     *
     * @time 2022/10/17 17:57
     * @param $id
     * @param Request $request
     * @return Response
     */
    public function update($id, Request $request): Response
    {
        return CatchResponse::success($this->visitPlanDetailModel->updateBy($id, $request->post()));
    }

    /**
     *
     * @time 2022/10/17 17:57
     * @param $id
     * @return Response
     */
    public function deleteById(CatchRequest $request): Response
    {
        try {
            $visitPlanIds = $request->param("visit_plan_ids", []);
            if (empty($visitPlanIds)) {
                throw new ValidateFailedException("计划id不能为空");
            }
            $type = $request->param("type", 1, "int");
            if ($type === 1) {
                $visitDetail = $this->visitPlanDetailModel->find($visitPlanIds[0]);
                $result = $this->visitPlanDetailModel->where([["id", "in", $visitPlanIds]])->save(["deleted_at" => time(), 'status' => -1]);
                if ($result !== false) {
                    $deletedCount = count($visitPlanIds);
                    (new \catchAdmin\visitPlan\model\VisitPlan())->where("id", "=", $visitDetail["visit_id"])->inc("receiv_count", $deletedCount * -1)->update();
                }
            } else {
                $result = $this->visitPlanDetailModel->where([["id", "in", $visitPlanIds]])->save(["is_stop" => 1]);
            }
            return CatchResponse::success($result);

        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }


    public function patientVisitPlan(\app\Request $request): \think\response\Json
    {

        $patientId = $request->param("patient_id", "", "string");
        if (trim(empty($patientId))) {
            throw new ValidateFailedException("患者id不能为空");
        }
        $dateArr = $request->param("date", []);

        $result = $this->visitPlanDetailModel->getDetailListByPatientId($patientId, $dateArr);
        return CatchResponse::success($result);
    }

    public function getVisitPlanDetailById(CatchRequest $request, string $id): \think\response\Json
    {
        $repeatArr = ["1" => "一周", "2" => "半个月", "3" => "一个月", "4" => "一季", "5" => "半年", "6" => "一年"];
        $result = $this->visitPlanDetailModel->find($id);
        if (!empty($result)) {
            #根据visitid获取主表内容
            $visitInfo = (new \catchAdmin\visitPlan\model\VisitPlan())->find($result["visit_id"]);
            if (!empty($visitInfo)) {
                $result["remind_count"] = $visitInfo["remind_count"];
                $result["remind_count_text"] = $visitInfo["remind_count"] . "天";
                $result["period"] = $visitInfo["period"];
                $result["visit_finish_time"] = $visitInfo["visit_finish_time"];
                $result["period_text"] = $repeatArr[$visitInfo["period"]] ?? "无";
            }
        }
        return CatchResponse::success($result);
    }


}